package net.ifilm.db;

import net.ifilm.common.SpiderException;
import net.ifilm.domain.Configuration;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DBConnectionUtil {

    private static DBConnectionUtil dbConnectionUtil = null;

    private boolean initStatus = false;
    private String dbDriver;
    private String dbUrl;
    private String dbUser;
    private String dbPass;

    private DBConnectionUtil() { }

    public void configuration(Configuration configuration)  throws Exception {
        if (initStatus) return;

        dbDriver = configuration.getDbDriver();
        dbUrl = configuration.getDbUrl();
        dbUser = configuration.getDbUser();
        dbPass = configuration.getDbPass();

        Class.forName(dbDriver);
    }

    public Connection getConnection() throws SpiderException {
        try {
            Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
            return conn;
        } catch (SQLException e) {
            throw new SpiderException(e.toString());
        }
    }

    public void freeResource(Connection conn, Statement statement, ResultSet rs) throws SpiderException {
        try {
            if (rs != null)  rs.close();
            if (statement != null) statement.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            throw new SpiderException(e.toString());
        }
    }

    public static DBConnectionUtil getInstance() {
        if (dbConnectionUtil == null) {
            dbConnectionUtil = new DBConnectionUtil();
        }
        return dbConnectionUtil;
    }

}
